package com.ca.ridersclubapplication.view.input;

import android.app.Dialog;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.ca.ridersclubapplication.R;
import com.ca.ridersclubapplication.UpdateActivity;
import com.ca.ridersclubapplication.request.dto.AccountUpdateDto;
import com.ea.ui.core.basic.EAButton;
import com.ea.ui.core.basic.EAInput;

import java.util.Objects;

public class TextValueEdit extends ConstraintLayout {

    public String type;

    public AccountUpdateDto dto;
    public UpdateActivity activity;
    public Dialog dialog;

    public TextView labelView;
    public EAInput inputView;
    public EAButton cancelButton;
    public EAButton okButton;

    public TextValueEdit(@NonNull Context context, String type, UpdateActivity activity, AccountUpdateDto dto) {
        super(context);

        this.type = type;
        this.activity = activity;
        this.dto = dto;

        initView(context);
    }

    public TextValueEdit(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public TextValueEdit(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.text_edit_layout, this);
        labelView = view.findViewById(R.id.tv_label);
        inputView = view.findViewById(R.id.ipt_text);
        cancelButton = view.findViewById(R.id.btn_cancel);
        okButton = view.findViewById(R.id.btn_ok);

        if ("nickname".equals(type)) {
            labelView.setText("昵称：");
            inputView.setText(dto.getNickname());
        }
        else if ("profile".equals(type)) {
            labelView.setText("简介：");
            inputView.setText(dto.getProfile());
        }

        cancelButton.setOnClickListener(v -> {
            dialog.dismiss();
        });

        okButton.setOnClickListener(v -> {

            if ("nickname".equals(type)) {
                String nickname = Objects.requireNonNull(inputView.getText()).toString();
                if (nickname.trim().isEmpty()) {
                    Toast.makeText(context, "请输入昵称", Toast.LENGTH_SHORT).show();
                    return;
                }

                dto.setNickname(nickname);
            }
            else if ("profile".equals(type)) {
                String profile = Objects.requireNonNull(inputView.getText()).toString();
                dto.setProfile(profile);
            }

            activity.update(dto);
            dialog.dismiss();
        });
    }
}
